package com.qingfeng.medical.biz.order.service.impl;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.qingfeng.medical.base.utils.ConstantPayPropertiesUtils;
import com.qingfeng.medical.base.utils.HttpClient;
import com.qingfeng.medical.biz.order.domain.entity.OrderInfo;
import com.qingfeng.medical.biz.order.domain.entity.PaymentInfo;
import com.qingfeng.medical.biz.order.domain.entity.RefundInfo;
import com.qingfeng.medical.biz.order.domain.enums.PaymentTypeEnum;
import com.qingfeng.medical.biz.order.domain.enums.RefundStatusEnum;
import com.qingfeng.medical.biz.order.service.OrderInfoService;
import com.qingfeng.medical.biz.order.service.PaymentInfoService;
import com.qingfeng.medical.biz.order.service.RefundInfoService;
import com.qingfeng.medical.biz.order.service.WeixinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 清风学Java
 * @version 1.0.0
 * @date 2022/7/26
 */
@Service
public class WeixinServiceImpl implements WeixinService {

    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private PaymentInfoService paymentInfoService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RefundInfoService refundInfoService;


    /**
     * 下单生成二维码
     *
     * @param orderId
     * @return
     */
    @Override
    public Map createNative(Long orderId) {
        try {
            Map payMap = (Map) redisTemplate.opsForValue().get(orderId.toString());
            if (null != payMap) {
                return payMap;
            }
            //根据id获取订单信息
            OrderInfo order = orderInfoService.getById(orderId);
            // 保存交易记录
            paymentInfoService.savePaymentInfo(order, PaymentTypeEnum.WECHAT);
            //1、设置参数
            Map<String, String> paramMap = MapUtil.builder(new HashMap<String, String>(16))
                    .put("appid", ConstantPayPropertiesUtils.APPID)
                    .put("mch_id", ConstantPayPropertiesUtils.PARTNER)
                    .put("nonce_str", WXPayUtil.generateNonceStr())
                    .put("body", order.getReserveDate() + "就诊" + order.getDepName() + "-" + order.getPatientName())
                    .put("out_trade_no", order.getOutTradeNo())
//                    .put("total_fee", order.getAmount().multiply(new BigDecimal("100")).longValue()+"");
                    //一分钱
                    .put("total_fee", "1")
                    .put("spbill_create_ip", "127.0.0.1")
                    .put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify")
                    .put("trade_type", "NATIVE")
                    .build();
            //2、HTTPClient来根据URL访问第三方接口并且传递参数
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //client设置参数
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPayPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            client.post();
            //3、返回第三方的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            //4、封装返回结果集
            Map map = MapUtil.builder(new HashMap(16))
                    .put("orderId", orderId)
                    .put("totalFee", order.getAmount())
                    .put("resultCode", resultMap.get("result_code"))
                    .put("codeUrl", resultMap.get("code_url"))
                    .build();
            if (null != resultMap.get("result_code")) {
                //微信支付二维码2小时过期，可采取2小时未支付取消订单
                redisTemplate.opsForValue().set(orderId.toString(), map, 120, TimeUnit.MINUTES);
            }
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return new HashMap<>(16);
        }
    }

    /**
     * 根据订单号去微信第三方查询支付状态
     *
     * @param orderId
     * @param paymentType
     * @return
     */
    @Override
    public Map<String, String> queryPayStatus(Long orderId, PaymentTypeEnum paymentType) {
        try {
            //1、根据orderId获取订单信息
            OrderInfo orderInfo = orderInfoService.getById(orderId);
            //2、封装提交参数
            Map<String, String> paramMap = MapUtil.builder(new HashMap<String, String>(16))
                    .put("appid", ConstantPayPropertiesUtils.APPID)
                    .put("mch_id", ConstantPayPropertiesUtils.PARTNER)
                    .put("out_trade_no", orderInfo.getOutTradeNo())
                    .put("nonce_str", WXPayUtil.generateNonceStr())
                    .build();
            //3、设置请求内容
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPayPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            client.post();
            //4、得到微信接口返回数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            System.out.println("resultMap: " + resultMap);
            //5、把接口数据返回
            return resultMap;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 退款
     *
     * @param orderId
     * @return
     */
    @Override
    public Boolean refund(Long orderId) {
        try {
            //获取支付记录信息
            PaymentInfo paymentInfoQuery = paymentInfoService.getPaymentInfo(orderId, PaymentTypeEnum.WECHAT);
            //添加信息到退款记录表中
            RefundInfo refundInfo = refundInfoService.saveRefundInfo(paymentInfoQuery);
            //判断当前订单数据是否已经退款
            if (refundInfo.getRefundStatus() == RefundStatusEnum.SUCCESS) {
                return true;
            }
            //调用微信接口实现退款
            //封装需要的参数
            Map<String, String> paramMap = MapUtil.builder(new HashMap<String, String>(16))
                    //公众账号ID
                    .put("appid", ConstantPayPropertiesUtils.APPID)
                    //商户编号
                    .put("mch_id", ConstantPayPropertiesUtils.PARTNER)
                    .put("nonce_str", WXPayUtil.generateNonceStr())
                    //微信订单号
                    .put("transaction_id", paymentInfoQuery.getTradeNo())
                    //商户订单编号
                    .put("out_trade_no", paymentInfoQuery.getOutTradeNo())
                    //商户退款单号
                    .put("out_refund_no", "tk" + paymentInfoQuery.getOutTradeNo())
                    //paramMap.put("total_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
                    //paramMap.put("refund_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
                    .put("total_fee", "1")
                    .put("refund_fee", "1")
                    .build();
            String paramXml = WXPayUtil.generateSignedXml(paramMap, ConstantPayPropertiesUtils.PARTNERKEY);
            //设置调用接口内容
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            client.setXmlParam(paramXml);
            client.setHttps(true);
            client.setCert(true);
            client.setCertPassword(ConstantPayPropertiesUtils.PARTNER);
            client.post();
            //3、返回第三方的数据
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            if (MapUtil.isNotEmpty(resultMap) && WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("result_code"))) {
                refundInfo.setCallbackTime(new Date());
                refundInfo.setTradeNo(resultMap.get("refund_id"));
                refundInfo.setRefundStatus(RefundStatusEnum.SUCCESS);
                refundInfo.setCallbackContent(JSONObject.toJSONString(resultMap));
                refundInfoService.updateById(refundInfo);
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


}
